//
//  SGFindPassWordBackViewController.m
//  HuaMuJinRong
//
//  Created by mac on 16/4/23.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "SGFindPassWordBackViewController.h"
#import "NSString+UserInfo.h"
#import "SGLoginTextField.h"
#import "SGRegisterViewController.h"
#import "SGLoginButton.h"

@interface SGFindPassWordBackViewController ()<HTTPClientDelegate>
@property (weak, nonatomic) IBOutlet SGLoginTextField *phoneNumTextField;
@property (weak, nonatomic) IBOutlet SGLoginTextField *phoneCodeTextField;
@property (weak, nonatomic) IBOutlet SGLoginTextField *passwordTextField;
@property (weak, nonatomic) IBOutlet SGLoginButton *sureButton;
@property (weak, nonatomic) IBOutlet UIButton *phoneCodeButton;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;

@property (nonatomic, strong) NetWorkClient *requestClient;

@end

@implementation SGFindPassWordBackViewController
{
    NSInteger requestType;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setNavBarBackgroundColor:[UIColor clearColor] andStatusBar:UIStatusBarStyleLightContent];
    
    [self initNavBarTitle:@"找回密码" andLeftItemName:@"返回" andRightItemName:@""];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
    [self resetNavigationBar];
    if (_requestClient) {
        [_requestClient cancel];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initData];
    [self initView];
}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)initView {
    
    _phoneNumTextField.font = KFontSize(14);
    _phoneCodeTextField.font = KFontSize(14);
    _passwordTextField.font = KFontSize(14);
    _phoneCodeButton.titleLabel.font = KFontSize(13);
    _sureButton.titleLabel.font = KFontSize(16);
    _registerButton.titleLabel.font = KFontSize(13);
    
    _sureButton.isActive = NO;
    _sureButton.clipsToBounds = YES;
    _sureButton.layer.cornerRadius = 4.0f;
    
    [_phoneNumTextField addTarget:self action:@selector(changeValue:) forControlEvents:UIControlEventEditingChanged];
    [_phoneCodeTextField addTarget:self action:@selector(changeValue:) forControlEvents:UIControlEventEditingChanged];
    [_passwordTextField addTarget:self action:@selector(changeValue:) forControlEvents:UIControlEventEditingChanged];
}

#pragma mark - Action
- (void)changeValue:(UITextField *)textField {
    if (_phoneNumTextField.text.length>0 && _phoneCodeTextField.text.length>0 && _passwordTextField.text.length>0) {
        _sureButton.isActive = YES;
    }else {
        _sureButton.isActive = NO;
    }
}

- (IBAction)phoneCodeButtonClick:(id)sender {
    
    if (_phoneNumTextField.text == nil || _phoneNumTextField.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号！"];
        return;
    }
    if (![NSString validateMobile:_phoneNumTextField.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号！"];
        return;
    }
    
    [self sendPhoneCodeRequest];
}

- (IBAction)nextButtonClick:(id)sender {
    
    if (_phoneNumTextField.text == nil || _phoneNumTextField.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号！"];
        return;
    }
    if (![NSString validateMobile:_phoneNumTextField.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号！"];
        return;
    }
    if (_phoneCodeTextField.text == nil || _phoneCodeTextField.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入验证码！"];
        return;
    }
    [self requestData];
}
- (IBAction)registerButtonClick:(id)sender {
    
    SGRegisterViewController *registerVc = [[SGRegisterViewController alloc] initWithNibName:@"SGRegisterViewController" bundle:nil];
    [self.navigationController pushViewController:registerVc animated:YES];
}

#pragma mark - Data
- (void)initData {
    
}

- (void)sendPhoneCodeRequest {
    requestType = 1;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    [parameters setObject:@"4" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:_phoneNumTextField.text forKey:@"cellPhone"];
    [parameters setObject:@"1" forKey:@"type"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
        
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

- (void)requestData {
    requestType = 2;
    
    NSString *newPassWord = [NSString encrypt3DES:_passwordTextField.text key:DESkey];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    //重置登录密码
    [parameters setObject:@"6" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:_phoneNumTextField.text forKey:@"cellPhone"];
    [parameters setObject:newPassWord forKey:@"newpwd"];
    [parameters setObject:_phoneCodeTextField.text forKey:@"randomCode"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

#pragma mark -------HTTPClientDelegate
- (void)startRequest {
    
}

- (void)httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
    NSDictionary *dics=(NSDictionary *)obj;
    NSString *errorStr=[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]];
    if ([errorStr isEqualToString:@"-1"]) {
        if (requestType == 1) {
            __block int timeout = DOWNTIME; //倒计时时间
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
            dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 1 * NSEC_PER_SEC);
            dispatch_source_set_event_handler(timer, ^{
                if(timeout<=0){ //倒计时结束，关闭
                    dispatch_source_cancel(timer);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //设置界面的按钮显示 根据自己需求设置
                        
                        [_phoneCodeButton setTitle:@"重新获取" forState:UIControlStateNormal];
                        _phoneCodeButton.userInteractionEnabled = YES;
                        [_phoneCodeButton setAlpha:1];
                    });
                }else{
                    int seconds = timeout % 60;
                    NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //设置界面的按钮显示 根据自己需求设置
                        
                        [_phoneCodeButton setTitle:[NSString stringWithFormat:@"%@秒",strTime] forState:UIControlStateNormal];
                        _phoneCodeButton.userInteractionEnabled = NO;
                        [_phoneCodeButton setAlpha:0.4];
                    });
                    timeout--;
                }
            });
            dispatch_resume(timer);

        }else {
            [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"%@",[dics objectForKey:@"msg"]]];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self back];
            });
        }
    }else{
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",[dics objectForKey:@"msg"]]];
    }
}

-(void) httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error {
//    [SVProgressHUD showErrorWithStatus:@"连接服务器失败，请稍后再试"];
}

-(void) networkError {
//    [SVProgressHUD showErrorWithStatus:@"网络不给力，请检查您的网络设置"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
